import { HOST } from '../constants/Config';



const timeOut = 1000 * 120;

const request = (url, options) => {
  console.log('options:' + JSON.stringify(options));
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      alert("连接超时")
      reject();
    }, timeOut);

    fetch(url, options)
      .then(res => {
        console.log(res);
        clearTimeout(timeoutId);
        return res.json();
      })
      .then(res => resolve(res))
      .catch(err => {
        console.log(err)
      });
  });
};

export const GET = (api, params) => {
  let url;

  if (params) {
    const stringifyParams = Object.keys(params)
      .reduce((acc, cur) => acc.concat([`${cur}=${params[cur]}`]), [])
      .join('&');
    url = `${HOST + api}?${stringifyParams}`;
  } else {
    url = HOST + api;
  }
  let tokenObj = {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=UTF-8',
      cnVer: 'V1',
      cnUser: 1568,
    },
  };
  return request(url, tokenObj);
};


export const POST = (api, params = {}) => {
  const url = HOST + api;
  const options = {
    method: 'POST',
    body: JSON.stringify(params),
  };
  let tokenObj = {
    headers: {
      "Access-Control-Allow-Origin": "*",
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=UTF-8',
      cnVer: 'V1',
      cnUser: 1568,
      token: global.token,
      userId: global.userId,
    },
  };
  return request(url, { ...tokenObj, ...options });
};